<?php


namespace app\guild\controller;


use app\common\model\GuildManagerModel;
use app\common\model\GuildRoleModel;
use think\Db;
use think\facade\Request;
use think\Validate;

class ManagerController extends BaseController {

    public function index() {
        return $this->fetch();
    }

    /**
     * 添加页面
     * @return mixed
     */
    public function add() {
        $guild_id = $this->guild_id;
        // 获取最后一个角色
        $last_role = GuildRoleModel::order('id', 'desc')->find();

        $where = [
            ['guild_id', '=', $guild_id],
            ['role_id', '<>', $last_role->id],
            ['role_id', '<>', 2],
        ];

        if ($this->hight_auth != 1) {
            $where[] = ['id', 'in', parent::getNextManager()];
        }
        $manager_list = GuildManagerModel::with('role')->where($where)->select();

        $this->assign('manager_list', $manager_list);
        $this->assign('hight_auth', $this->hight_auth);
        return $this->fetch();
    }

    public function edit() {
        $guild_id = $this->guild_id;
        $id       = Request::param('id');

        $where = [
            "id=$id",
            "guild_id=$guild_id",
        ];
        if ($this->hight_auth != 1) {
            $where[] = "(FIND_IN_SET({$this->manager_id},path_ids) OR id={$this->manager_id})";
        }
        $where        = implode(' AND ', $where);
        $manager_info = GuildManagerModel::where($where)->find();
        if (empty($manager_info)) {
            $this->error('未查询到相关成员信息');
        }

        // // 获取最后一个角色
        // $last_role = GuildRoleModel::order('id', 'desc')->find();
        //
        // $where = [
        //     ['guild_id', '=', $guild_id],
        //     ['role_id', '<>', $last_role->id],
        //     ['role_id', '<>', 2],
        // ];
        //
        // if ($this->hight_auth != 1) {
        //     if ($this->manager_id == $manager_info->id) {
        //         $this->error('暂不支持当前成员信息的编辑');
        //     }
        //
        //     $where[] = ['id', 'in', parent::getNextManager()];
        // }
        $manager_list = GuildManagerModel::with('role')->where($where)->select();

        $this->assign('manager_info', $manager_info);
        $this->assign('manager_list', $manager_list);
        $this->assign('hight_auth', $this->hight_auth);
        return $this->fetch();
    }

    /**
     * 成员列表
     * @return \think\response\Json
     */
    public function get_list() {
        $page     = Request::param("page");
        $limit    = Request::param("limit");
        $mobile   = Request::param("mobile");
        $guild_id = $this->guild_id;

        $where = [
            ['guild_id', '=', $guild_id]
        ];
        if ($this->hight_auth != 1) {
            $where[] = ['', 'EXP', Db::raw("FIND_IN_SET({$this->manager_id},path_ids)")];
        }
        if (mb_strlen($mobile) > 0) {
            $where[] = ['mobile', 'like', "%{$mobile}%"];
        }

        $list = GuildManagerModel::with(['role', 'parent'])->where($where)->whereOr('id',$this->manager_id)->field('password,token', true)
            ->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($list) > 0) {
            $count = GuildManagerModel::where($where)->whereOr('id',$this->manager_id)->count();

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 添加成员
     * @return \think\response\Json
     */
    public function add_post() {
        $all_param = Request::param();
        $password  = Request::param('password');
        $parent_id = Request::param('parent_id');
        // 账号类型 1管理员 2经纪人
        $account_type = Request::param('account_type');
        $guild_id     = $this->guild_id;

        if ($this->hight_auth != 1) {
            $account_type = 2;
        }

        // 查询除了管理员的其他角色成员
        $m_where     = [
            ['guild_id', '=', $guild_id],
            ['role_id', '<>', 2],
        ];
        $manager_ids = GuildManagerModel::where($m_where)->column('id');
        $manager_ids = implode(',', $manager_ids);

        $validate_check = [
            'mobile'    => 'require|pass:' . config('other.mobile_preg'),
            'password'  => 'require|pass:/^[\S]{6,12}$/',
            'real_name' => 'require|length:2,16|chsDash',
        ];
        $validate_msg   = [
            "mobile.require"    => "请输入手机号",
            "mobile.pass"       => "请输入正确的手机号",
            "password.require"  => "请输入密码",
            "password.pass"     => "密码在6-12位且不能有空格",
            "real_name.require" => "请输入真实姓名",
            "real_name.length"  => "真实姓名在2-16个字符",
            "real_name.chsDash" => "真实姓名中文、英文、_和-组成",
        ];

        if ($this->hight_auth == 1) {
            $validate_check['account_type']       = "require|in:1,2";
            $validate_msg['account_type.require'] = "请选择账号类型";
            $validate_msg['account_type.in']      = "账号类型选择错误";
        }

        // 选择经纪人验证
        if ($account_type == 2) {
            $validate_check['parent_id']       = "require|in:$manager_ids";
            $validate_msg['parent_id.require'] = "请正确选择直属上级";
            $validate_msg['parent_id.in']      = "请正确选择直属上级";

            $validate_check['sharing_ratio']       = "require|integer|between:0,100";
            $validate_msg['sharing_ratio.require'] = "请输入分成比例";
            $validate_msg['sharing_ratio.integer'] = "分成比例只能为整数";
            $validate_msg['sharing_ratio.between'] = "分成比例只能在0-100范围内";
        }

        $validate = new Validate($validate_check, $validate_msg);
        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $guild_manager = new GuildManagerModel($all_param);

        //检测手机号是否占用
        $check = GuildManagerModel::get(["mobile" => $guild_manager->mobile]);
        if ($check) {
            return self::bulidFail("手机号已被占用");
        }

        // 上级成员id 如果添加的是管理员无需设置上级id
        $parent_id = !empty($parent_id) ? $parent_id : 0;
        $parent_id = $account_type == 1 ? 0 : $parent_id;

        $guild_manager->role_id = 2;
        if ($account_type == 2) {
            // 查询直属上级
            $parent_info = GuildManagerModel::get($parent_id);
            if (empty($parent_info)) {
                return self::bulidFail("直属上级不存在");
            }

            // 查询下级角色信息
            $next_role = GuildRoleModel::where('id', '>', $parent_info->role_id)->where('id', '<>', 2)->order('id', 'asc')->find();
            if (empty($next_role)) {
                return self::bulidFail("角色信息错误");
            }

            // 获取最后一个角色
            $last_role = GuildRoleModel::order('id', 'desc')->find();

            if ($next_role->id > $last_role->id) {
                return self::bulidFail("角色信息只能选择到{$last_role->name}");
            }

            // 角色id
            $guild_manager->role_id = $next_role->id;
        }

        // 所有上级id
        $path_ids = empty($parent_info->path_ids) ? '0' : $parent_info->path_ids;
        if ($account_type == 2) {
            $path_ids .= ',' . $parent_id;
        }

        // 组合所有上级id
        $guild_manager->path_ids    = $path_ids;
        $guild_manager->parent_id   = $parent_id;
        $guild_manager->guild_id    = $this->guild_id;
        $guild_manager->password    = openssl_encrypt(substr($guild_manager->mobile, strlen($guild_manager->mobile) - 4, 4) . $password, "DES-ECB", $this->OPENSSL_KEY);
        $guild_manager->create_time = date("Y-m-d H:i:s");
        // 管理员无需设置分成
        if ($guild_manager->role_id < 3) {
            $guild_manager->sharing_ratio = 0;
        }

        if ($guild_manager->save()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function edit_post() {
        $all_param = Request::param();
        $password  = Request::param('password');
        $id        = Request::param('id');
        $guild_id  = $this->guild_id;

        $validate = new Validate([
            'mobile'        => 'require|pass:' . config('other.mobile_preg'),
            'real_name'     => 'require|length:2,16|chsDash',
            'sharing_ratio' => 'require|integer|between:0,100',
        ], [
            "mobile.require"        => "请输入手机号",
            "mobile.pass"           => "请输入正确的手机号",
            "real_name.require"     => "请输入真实姓名",
            "real_name.length"      => "真实姓名在2-16个字符",
            "real_name.chsDash"     => "真实姓名中文、英文、_和-组成",
            "sharing_ratio.require" => "请输入分成比例",
            "sharing_ratio.integer" => "分成比例只能为整数",
            "sharing_ratio.between" => "分成比例只能在0-100范围内",
        ]);
        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        // 查询成员信息是否存在
        $manager_info = GuildManagerModel::where(['id' => $id, 'guild_id' => $guild_id])->find();
        if (empty($manager_info)) {
            return self::bulidFail("成员信息不存在");
        }

        if ($this->hight_auth != 1) {
            // 下级所有成员id
            $next_manager = self::getNextManager();
            if (!in_array($manager_info->id, $next_manager)) {
                return self::bulidFail("暂不支持当前成员信息的编辑");
            }
        }

        //检测手机号是否占用
        $c_where = [
            ['id', '<>', $id],
            ['mobile', '=', $all_param['mobile']],
        ];
        $check   = GuildManagerModel::where($c_where)->find();
        if ($check) {
            return self::bulidFail("手机号已被占用");
        }

        $manager_info->sharing_ratio = $all_param['sharing_ratio'];
        $manager_info->mobile        = $all_param['mobile'];
        $manager_info->real_name     = $all_param['real_name'];
        // 组合所有上级id
        if ($password) {
            if (!preg_match('/^[\S]{6,12}$/', $password)) {
                return self::bulidFail("密码在6-12位且不能有空格");
            }

            $manager_info->password = openssl_encrypt(substr($manager_info->mobile, strlen($manager_info->mobile) - 4, 4) . $password, "DES-ECB", $this->OPENSSL_KEY);
        }

        // 管理员无需设置分成
        if ($manager_info->role_id < 3) {
            $manager_info->sharing_ratio = 0;
        }

        if ($manager_info->save()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }


}